//
//  MBChatPlayerView.m
//  Meboo
//
//  Created by kyo on 2023/10/20.
//

#import "MBChatPlayerView.h"
#import <AVFoundation/AVFoundation.h>
@interface MBChatPlayerView ()

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer*playerLayer;
@property (nonatomic, strong) AVPlayerItem *playerItem;
@property (nonatomic, strong) UISlider *progressSliderView;

@property (nonatomic, strong) UIButton *playBtn;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UILabel *currentTimeLab;
@property (nonatomic, strong) UILabel *totalTimeLab;
@property (nonatomic, strong) UIButton *smallPlayBtn;

@property (nonatomic, strong)NSDateFormatter *dateFormatter;

@property (nonatomic, assign)CGFloat currentTime;

@property (nonatomic, assign)BOOL isPause;

@end

@implementation MBChatPlayerView

#pragma mark - Life Cycle
- (instancetype)initWithUrl:(NSURL *)videoUrl {
    if (self = [super init]) {
        self.videoUrl = videoUrl;
        [self setupUI];
        self.totalTime =  [self duration];
        self.totalTimeLab.text = [self convertTime:self.totalTime];
    }
    return self;
}

- (void)setVideoUrl:(NSURL *)videoUrl {
    _videoUrl = videoUrl;
    self.playerItem = [[AVPlayerItem alloc] initWithURL:self.videoUrl];
}

/**
 *  跳到time处播放
 *  @param seekTime这个时刻，这个时间点
 */
- (void)seekToTimeToPlay:(double)time{
    if (self.player&&self.player.currentItem.status == AVPlayerItemStatusReadyToPlay) {
        if (time>[self duration]) {
            time = [self duration];
        }
        if (time<=0) {
            time=0.0;
        }
        //        int32_t timeScale = self.player.currentItem.asset.duration.timescale;
        //currentItem.asset.duration.timescale计算的时候严重堵塞主线程，慎用
        /* A timescale of 1 means you can only specify whole seconds to seek to. The timescale is the number of parts per second. Use 600 for video, as Apple recommends, since it is a product of the common video frame rates like 50, 60, 25 and 24 frames per second*/
        
        //        [self.player seekToTime:CMTimeMakeWithSeconds(time, _currentItem.currentTime.timescale) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
        //
        //        }];
        
        
    }
}

/**
 * 把秒转换成格式
 **/
- (NSString *)convertTime:(CGFloat)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    if (second/3600 >= 1) {
        [[self dateFormatter] setDateFormat:@"HH:mm:ss"];
    } else {
        [[self dateFormatter] setDateFormat:@"mm:ss"];
    }
    NSString *newTime = [[self dateFormatter] stringFromDate:d];
    return newTime;
}

/**
 * 获取视频长度
 **/
- (double)duration{
    return CMTimeGetSeconds([[self.playerItem asset] duration]);
}

/**
 * 时间转换格式
 **/
- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
    }
    return _dateFormatter;
}

#pragma mark - Action

- (void)playAction {
    self.playBtn.hidden = YES;
    if (self.playBtn.hidden) {
        [self.smallPlayBtn setImage:ImageWithName(@"chat_send_video_pausesmall") forState:0];
    } else {
        [self.smallPlayBtn setImage:ImageWithName(@"chat_send_video_playsmall") forState:0];
    }
    [self.player seekToTime:CMTimeMake(self.currentTime, 1)];
    [self.player play];
    [NSTimer scheduledTimerWithTimeInterval:1
                                     target:self
                                   selector:@selector(progressChanged:)
                                   userInfo:nil
                                    repeats:YES];
}

- (void)smallPlayAction {
    if (self.playBtn.hidden) {
        self.playBtn.hidden = NO;
        [self.smallPlayBtn setImage:ImageWithName(@"chat_send_video_playsmall") forState:0];
        [self.player pause];
    } else {
        [self playAction];
    }
}

-(void)progressChanged:(NSTimer *)timer {
    if (!self.playBtn.hidden) {
        [timer invalidate];
    }

    self.currentTime += 1.0;
    self.currentTimeLab.text = [self convertTime:self.currentTime];
    self.progressSliderView.value = self.currentTime/self.totalTime;
    if (self.self.currentTime == self.totalTime) {
        [self.smallPlayBtn setImage:ImageWithName(@"chat_send_video_playsmall") forState:0];
        self.playBtn.hidden = NO;
        self.currentTime = 0;
        self.progressSliderView.value = 0;
        self.currentTimeLab.text = @"00:00";
        [timer invalidate];
    }
}

#pragma mark - UI
- (void)setupUI {
    
    self.backgroundColor = HEXS(@"22253C");
    CGFloat maxHeight = ScreenHeight-TabbarSafeBottomMargin-MBHeightScale(89)-MBHeightScale(34)-StatusBarAndNavigationBarHeight;
    
    self.playerLayer.frame = CGRectMake(0, 0, ScreenWidth, maxHeight);
    [self.layer addSublayer:self.playerLayer];
    
    [self addSubview:self.playBtn];
    [self.playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.mas_equalTo(MBHeightScale(101));
        make.height.mas_equalTo(MBHeightScale(101));
    }];
    
    [self addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.height.mas_equalTo(MBHeightScale(46));
    }];
    
    [self.bottomView addSubview:self.smallPlayBtn];
    [self.smallPlayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.bottomView);
        make.left.mas_equalTo(MBWidthScale(10));
        make.height.width.mas_equalTo(MBHeightScale(18));
    }];
    
    [self.bottomView addSubview:self.currentTimeLab];
    [self.currentTimeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.bottomView);
        make.left.equalTo(self.smallPlayBtn.mas_right).offset(MBWidthScale(8));
    }];
    
    [self.bottomView addSubview:self.totalTimeLab];
    [self.totalTimeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.bottomView);
        make.right.mas_equalTo(MBWidthScale(-10));
    }];
    
    [self.bottomView addSubview:self.progressSliderView];
    [self.progressSliderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.bottomView);
        make.left.equalTo(self.currentTimeLab.mas_right).offset(MBWidthScale(8));
        make.right.equalTo(self.totalTimeLab.mas_left).offset(MBWidthScale(-8));
    }];
}

#pragma mark - Setter && Getter
- (UIButton *)playBtn {
    if (!_playBtn) {
        _playBtn = [[UIButton alloc] init];
        [_playBtn setImage:ImageWithName(@"chat_send_video_play") forState:0];
        [_playBtn addTarget:self action:@selector(playAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _playBtn;
}

- (AVPlayer *)player{
    if(!_player){
        _player = [AVPlayer playerWithPlayerItem:self.playerItem];
    }
    return _player;
}

- (AVPlayerItem *)playerItem {
    if(!_playerItem) {
        _playerItem = [[AVPlayerItem alloc] initWithURL:self.videoUrl];
    }
    return _playerItem;
}

- (AVPlayerLayer *)playerLayer{
    if(!_playerLayer){
        _playerLayer  = [AVPlayerLayer playerLayerWithPlayer:self.player];
        _playerLayer.videoGravity =AVLayerVideoGravityResizeAspectFill;
    }
    return _playerLayer;
}

- (UISlider *)progressSliderView {
    if (!_progressSliderView) {
        _progressSliderView = [UISlider new];
        _progressSliderView.userInteractionEnabled = NO;
        _progressSliderView.minimumTrackTintColor = [UIColor colorWithRed:255 / 255.0 green:255 / 255.0 blue:255 / 255.0 alpha:1];
        _progressSliderView.maximumTrackTintColor = [UIColor colorWithRed:255 / 255.0 green:255 / 255.0 blue:255 / 255.0 alpha:0.8];
        [_progressSliderView setThumbImage:ImageWithName(@"chat_send_video_slider") forState:0];
    }
    return _progressSliderView;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [UIView new];
        _bottomView.backgroundColor = [UIColor colorWithRed:0 / 255.0 green:0 / 255.0 blue:0 / 255.0 alpha:0.2];
    }
    return _bottomView;
}

- (UIButton *)smallPlayBtn {
    if (!_smallPlayBtn) {
        _smallPlayBtn = [[UIButton alloc] init];
        [_smallPlayBtn setImage:ImageWithName(@"chat_send_video_playsmall") forState:0];
        [_smallPlayBtn addTarget:self action:@selector(smallPlayAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _smallPlayBtn;
}

- (UILabel *)currentTimeLab {
    if (!_currentTimeLab) {
        _currentTimeLab = [[UILabel alloc] init];
        _currentTimeLab.font = MBFontSizeScale(16);
        _currentTimeLab.text = @"00:00";
        _currentTimeLab.textColor = UIColor.whiteColor;
    }
    return _currentTimeLab;
}

- (UILabel *)totalTimeLab {
    if (!_totalTimeLab) {
        _totalTimeLab = [[UILabel alloc] init];
        _totalTimeLab.font = MBFontSizeScale(16);
        _totalTimeLab.textColor = UIColor.whiteColor;
        _totalTimeLab.text = @"00:00";
    }
    return _totalTimeLab;
}
@end
